using CollabApp.Domain.Entities.Room;
using CollabApp.Domain.Services.Room;
using CollabApp.Domain.Repositories;
using CollabApp.Domain.Entities.Auth;
using CollabApp.Application.Interfaces;
using CollabApp.Application.DTOs.Game;
using Microsoft.Extensions.Logging;

namespace CollabApp.Application.Services.Room;

/// <summary>
/// 房间服务实现
/// </summary>
public class RoomService : IRoomService
{
    private readonly IRepository<Domain.Entities.Room.Room> _roomRepository;
    private readonly IRepository<User> _userRepository;
    private readonly IRepository<RoomPlayer> _roomPlayerRepository;
    private readonly IRepository<RoomMessage> _roomMessageRepository;
    private readonly ILineDrawingGameService _lineDrawingGameService;
    private readonly ILogger<RoomService> _logger;

    public RoomService(
        IRepository<Domain.Entities.Room.Room> roomRepository,
        IRepository<User> userRepository,
        IRepository<RoomPlayer> roomPlayerRepository,
        IRepository<RoomMessage> roomMessageRepository,
        ILineDrawingGameService lineDrawingGameService,
        ILogger<RoomService> logger)
    {
        _roomRepository = roomRepository;
        _userRepository = userRepository;
        _roomPlayerRepository = roomPlayerRepository;
        _roomMessageRepository = roomMessageRepository;
        _lineDrawingGameService = lineDrawingGameService;
        _logger = logger;
    }

    public async Task<Domain.Entities.Room.Room> CreateRoomAsync(
        string name, 
        Guid ownerId, 
        int maxPlayers = 4, 
        string? password = null, 
        bool isPrivate = false, 
        string? settings = null)
    {
        try
        {
            _logger.LogInformation("创建房间 - 名称: {Name}, 房主ID: {OwnerId}", name, ownerId);

            // 验证房主用户是否存在
            var owner = await _userRepository.GetByIdAsync(ownerId);
            if (owner == null)
            {
                throw new ArgumentException("房主用户不存在", nameof(ownerId));
            }

            // 创建房间实体
            var room = Domain.Entities.Room.Room.CreateRoom(
                name, 
                ownerId, 
                maxPlayers, 
                password, 
                isPrivate, 
                settings);

            await _roomRepository.AddAsync(room);
            await _roomRepository.SaveChangesAsync();

            // 自动将房主加入房间
            var joinResult = await JoinRoomAsync(room.Id, ownerId);
            if (!joinResult.Success)
            {
                _logger.LogWarning("房间创建成功但房主自动加入失败 - RoomId: {RoomId}, OwnerId: {OwnerId}, Errors: {Errors}", 
                    room.Id, ownerId, string.Join("; ", joinResult.Errors));
            }

            _logger.LogInformation("房间创建成功并房主已自动加入 - ID: {RoomId}", room.Id);
            return room;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建房间失败 - 名称: {Name}, 房主ID: {OwnerId}", name, ownerId);
            throw;
        }
    }

    public async Task<PagedResult<RoomListItem>> GetRoomListAsync(
        int pageNumber = 1, 
        int pageSize = 20, 
        bool includePrivate = false, 
        RoomStatus? statusFilter = null)
    {
        try
        {
            _logger.LogInformation("获取房间列表 - 页码: {PageNumber}, 页大小: {PageSize}", pageNumber, pageSize);

            var pageIndex = pageNumber - 1;

            // 构建查询条件
            var rooms = await _roomRepository.GetManyAsync(r => 
                (includePrivate || !r.IsPrivate) &&
                (statusFilter == null || r.Status == statusFilter) &&
                r.CurrentPlayers > 0 &&  // 过滤掉0玩家的房间
                !r.IsDeleted);           // 过滤掉已删除的房间

            var totalCount = rooms.Count();
            var pagedRooms = rooms.Skip(pageIndex * pageSize).Take(pageSize).ToList();

            var roomItems = new List<RoomListItem>();
            foreach (var room in pagedRooms)
            {
                var owner = await _userRepository.GetByIdAsync(room.OwnerId);
                roomItems.Add(new RoomListItem
                {
                    Id = room.Id,
                    Name = room.Name,
                    OwnerName = owner?.Nickname ?? "未知用户",
                    CurrentPlayers = room.CurrentPlayers,  // 直接使用CurrentPlayers字段
                    MaxPlayers = room.MaxPlayers,
                    Status = room.Status,
                    IsPrivate = room.IsPrivate,
                    HasPassword = !string.IsNullOrEmpty(room.Password),
                    CreatedAt = room.CreatedAt
                });
            }

            return new PagedResult<RoomListItem>
            {
                Items = roomItems,
                TotalCount = totalCount,
                PageNumber = pageNumber,
                PageSize = pageSize
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取房间列表失败");
            throw;
        }
    }

    public async Task<RoomDetail?> GetRoomDetailAsync(Guid roomId, Guid userId)
    {
        try
        {
            var room = await _roomRepository.GetByIdAsync(roomId);
            if (room == null)
            {
                return null;
            }

            var owner = await _userRepository.GetByIdAsync(room.OwnerId);
            var players = new List<RoomPlayerInfo>();

            // 从RoomPlayer表获取玩家信息
            var roomPlayers = await _roomPlayerRepository.GetManyAsync(rp => rp.RoomId == roomId);
            foreach (var player in roomPlayers)
            {
                var user = await _userRepository.GetByIdAsync(player.UserId);
                if (user != null)
                {
                    players.Add(new RoomPlayerInfo
                    {
                        UserId = user.Id,
                        UserName = user.Nickname,
                        Avatar = user.AvatarUrl,
                        IsReady = player.IsReady,
                        IsOwner = player.UserId == room.OwnerId,
                        PlayerColor = player.PlayerColor,
                        JoinedAt = player.CreatedAt // 使用 CreatedAt 作为加入时间
                    });
                }
            }

            return new RoomDetail
            {
                Id = room.Id,
                Name = room.Name,
                OwnerId = room.OwnerId,
                OwnerName = owner?.Nickname ?? "未知用户",
                CurrentPlayers = players.Count,
                MaxPlayers = room.MaxPlayers,
                Status = room.Status,
                IsPrivate = room.IsPrivate,
                HasPassword = !string.IsNullOrEmpty(room.Password),
                CreatedAt = room.CreatedAt,
                Settings = room.Settings,
                Players = players
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取房间详情失败 - RoomId: {RoomId}", roomId);
            throw;
        }
    }

    public async Task<JoinRoomResult> JoinRoomAsync(Guid roomId, Guid userId, string? password = null)
    {
        try
        {
            var room = await _roomRepository.GetByIdAsync(roomId);
            if (room == null)
            {
                return new JoinRoomResult
                {
                    Success = false,
                    Message = "房间不存在",
                    Errors = { "房间不存在" }
                };
            }

            // 验证房间状态
            if (room.Status != RoomStatus.Waiting)
            {
                return new JoinRoomResult
                {
                    Success = false,
                    Message = "房间状态不允许加入",
                    Errors = { "房间状态不允许加入" }
                };
            }

            // 验证密码
            if (!room.CheckPassword(password))
            {
                return new JoinRoomResult
                {
                    Success = false,
                    Message = "房间密码错误",
                    Errors = { "房间密码错误" }
                };
            }

            // 验证房间是否已满
            if (room.CurrentPlayers >= room.MaxPlayers)
            {
                return new JoinRoomResult
                {
                    Success = false,
                    Message = "房间已满",
                    Errors = { "房间已满" }
                };
            }

            // 检查用户是否已在房间中（包括软删除的记录）
            var existingPlayer = await _roomPlayerRepository.GetSingleAsync(rp => rp.RoomId == roomId && rp.UserId == userId);
            if (existingPlayer != null)
            {
                return new JoinRoomResult
                {
                    Success = false,
                    Message = "您已在此房间中",
                    Errors = { "您已在此房间中" }
                };
            }

            // 检查是否存在已软删除的记录，如果有，重新激活而不是创建新记录
            // 使用原生查询来检查软删除的记录
            var softDeletedPlayerQuery = await _roomPlayerRepository.GetManyAsync(rp => true); // 获取所有记录
            var allPlayers = softDeletedPlayerQuery.ToList();
            var softDeletedPlayer = allPlayers.FirstOrDefault(p => p.RoomId == roomId && p.UserId == userId && p.IsDeleted);

            if (softDeletedPlayer != null)
            {
                // 重新激活已软删除的记录
                softDeletedPlayer.IsDeleted = false;
                softDeletedPlayer.SetReady(false); // 重置准备状态
                softDeletedPlayer.UpdatedAt = DateTime.UtcNow;
                
                // 重新分配加入顺序和颜色
                var currentPlayersInRoom = await _roomPlayerRepository.GetManyAsync(rp => rp.RoomId == roomId);
                var playersList = currentPlayersInRoom.ToList();
                softDeletedPlayer.SetJoinOrder(playersList.Count + 1);
                softDeletedPlayer.SetPlayerColor(GetNextAvailableColor(playersList));

                await _roomPlayerRepository.UpdateAsync(softDeletedPlayer);
                await _roomPlayerRepository.SaveChangesAsync();

                // 更新房间的玩家数量
                room.IncrementPlayerCount();
                await _roomRepository.UpdateAsync(room);
                await _roomRepository.SaveChangesAsync();

                var reactivatedRoomDetail = await GetRoomDetailAsync(roomId, userId);
                return new JoinRoomResult
                {
                    Success = true,
                    Message = "成功重新加入房间",
                    RoomDetail = reactivatedRoomDetail
                };
            }

            // 验证用户是否存在
            var user = await _userRepository.GetByIdAsync(userId);
            if (user == null)
            {
                return new JoinRoomResult
                {
                    Success = false,
                    Message = "用户不存在",
                    Errors = { "用户不存在" }
                };
            }

            // 获取当前房间玩家数量
            var currentActivePlayersInRoom = await _roomPlayerRepository.GetManyAsync(rp => rp.RoomId == roomId);
            var activePlayersList = currentActivePlayersInRoom.ToList();

            // 创建新的RoomPlayer记录
            var roomPlayer = RoomPlayer.CreateRoomPlayer(
                roomId, 
                userId, 
                activePlayersList.Count + 1, // 设置加入顺序
                GetNextAvailableColor(activePlayersList)
            );

            await _roomPlayerRepository.AddAsync(roomPlayer);
            await _roomPlayerRepository.SaveChangesAsync();

            // 更新房间的玩家数量
            room.IncrementPlayerCount();
            await _roomRepository.UpdateAsync(room);
            await _roomRepository.SaveChangesAsync();

            var roomDetail = await GetRoomDetailAsync(roomId, userId);
            return new JoinRoomResult
            {
                Success = true,
                Message = "成功加入房间",
                RoomDetail = roomDetail
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "加入房间失败 - RoomId: {RoomId}, UserId: {UserId}", roomId, userId);
            return new JoinRoomResult
            {
                Success = false,
                Message = "加入房间失败",
                Errors = { ex.Message }
            };
        }
    }

    public async Task<LeaveRoomResult> LeaveRoomAsync(Guid roomId, Guid userId)
    {
        try
        {
            var room = await _roomRepository.GetByIdAsync(roomId);
            if (room == null)
            {
                return new LeaveRoomResult
                {
                    Success = false,
                    Message = "房间不存在",
                    Errors = { "房间不存在" }
                };
            }

            var player = await _roomPlayerRepository.GetSingleAsync(rp => rp.RoomId == roomId && rp.UserId == userId);
            if (player == null)
            {
                return new LeaveRoomResult
                {
                    Success = false,
                    Message = "您不在此房间中",
                    Errors = { "您不在此房间中" }
                };
            }

            var roomDeleted = false;
            var newOwnerId = Guid.Empty;
            
            if (room.OwnerId == userId)
            {
                // 房主离开，先获取其他玩家（在删除当前玩家之前）
                var remainingPlayers = await _roomPlayerRepository.GetManyAsync(rp => rp.RoomId == roomId && rp.UserId != userId);
                var remainingPlayersList = remainingPlayers.ToList();
                
                if (remainingPlayersList.Count > 0)
                {
                    // 还有其他玩家，将房主权限转移给第一个加入的玩家
                    var newOwner = remainingPlayersList.OrderBy(p => p.CreatedAt).First();
                    newOwnerId = newOwner.UserId;
                    
                    room.TransferOwnership(newOwnerId);
                    
                    _logger.LogInformation("房主权限已转移 - 原房主: {OldOwnerId}, 新房主: {NewOwnerId}, 房间: {RoomId}", 
                        userId, newOwnerId, roomId);
                }
                else
                {
                    // 房间无其他玩家时标记删除房间
                    roomDeleted = true;
                    _logger.LogInformation("房间将被删除 - RoomId: {RoomId}, 原因: 无剩余玩家", roomId);
                }
            }

            // 删除玩家记录
            await _roomPlayerRepository.DeleteAsync(player);
            await _roomPlayerRepository.SaveChangesAsync();
            
            // 同步更新CurrentPlayers字段
            room.DecrementPlayerCount();

            if (roomDeleted)
            {
                // 删除房间
                await _roomRepository.DeleteAsync(roomId);
            }
            else
            {
                // 更新房间信息
                await _roomRepository.UpdateAsync(room);
            }

            await _roomRepository.SaveChangesAsync();

            var message = roomDeleted 
                ? "房间已解散" 
                : newOwnerId != Guid.Empty 
                    ? "成功离开房间，房主权限已转移" 
                    : "成功离开房间";

            return new LeaveRoomResult
            {
                Success = true,
                Message = message,
                RoomDeleted = roomDeleted,
                NewOwnerId = newOwnerId != Guid.Empty ? newOwnerId : null
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "离开房间失败 - RoomId: {RoomId}, UserId: {UserId}", roomId, userId);
            return new LeaveRoomResult
            {
                Success = false,
                Message = "离开房间失败",
                Errors = { ex.Message }
            };
        }
    }

    public async Task<UpdateRoomResult> UpdateRoomAsync(
        Guid roomId, 
        Guid userId, 
        string? name = null, 
        int? maxPlayers = null, 
        string? password = null, 
        bool? isPrivate = null, 
        string? settings = null)
    {
        try
        {
            var room = await _roomRepository.GetByIdAsync(roomId);
            if (room == null)
            {
                return new UpdateRoomResult
                {
                    Success = false,
                    Message = "房间不存在",
                    Errors = { "房间不存在" }
                };
            }

            if (room.OwnerId != userId)
            {
                return new UpdateRoomResult
                {
                    Success = false,
                    Message = "只有房主可以修改房间设置",
                    Errors = { "只有房主可以修改房间设置" }
                };
            }

            // 更新房间信息
            room.UpdateRoomInfo(name, maxPlayers, password, isPrivate, settings);

            await _roomRepository.UpdateAsync(room);
            await _roomRepository.SaveChangesAsync();

            var roomDetail = await GetRoomDetailAsync(roomId, userId);
            return new UpdateRoomResult
            {
                Success = true,
                Message = "房间信息更新成功",
                RoomDetail = roomDetail
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新房间失败 - RoomId: {RoomId}", roomId);
            return new UpdateRoomResult
            {
                Success = false,
                Message = "更新房间失败",
                Errors = { ex.Message }
            };
        }
    }

    public async Task<DeleteRoomResult> DeleteRoomAsync(Guid roomId, Guid userId)
    {
        try
        {
            var room = await _roomRepository.GetByIdAsync(roomId);
            if (room == null)
            {
                return new DeleteRoomResult
                {
                    Success = false,
                    Message = "房间不存在",
                    Errors = { "房间不存在" }
                };
            }

            if (room.OwnerId != userId)
            {
                return new DeleteRoomResult
                {
                    Success = false,
                    Message = "只有房主可以删除房间",
                    Errors = { "只有房主可以删除房间" }
                };
            }

            await _roomRepository.DeleteAsync(roomId);
            await _roomRepository.SaveChangesAsync();

            return new DeleteRoomResult
            {
                Success = true,
                Message = "房间删除成功"
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除房间失败 - RoomId: {RoomId}", roomId);
            return new DeleteRoomResult
            {
                Success = false,
                Message = "删除房间失败",
                Errors = { ex.Message }
            };
        }
    }

    public async Task<SetReadyResult> SetPlayerReadyAsync(Guid roomId, Guid userId, bool isReady)
    {
        try
        {
            var room = await _roomRepository.GetByIdAsync(roomId);
            if (room == null)
            {
                return new SetReadyResult
                {
                    Success = false,
                    Message = "房间不存在",
                    Errors = { "房间不存在" }
                };
            }

            var player = await _roomPlayerRepository.GetSingleAsync(rp => rp.RoomId == roomId && rp.UserId == userId);
            if (player == null)
            {
                return new SetReadyResult
                {
                    Success = false,
                    Message = "您不在此房间中",
                    Errors = { "您不在此房间中" }
                };
            }

            player.SetReady(isReady);
            await _roomPlayerRepository.UpdateAsync(player);
            await _roomPlayerRepository.SaveChangesAsync();

            // 检查是否所有玩家都准备好了
            var allPlayers = await _roomPlayerRepository.GetManyAsync(rp => rp.RoomId == roomId);
            var playersList = allPlayers.ToList();
            var canStartGame = playersList.Count >= 2 && playersList.All(p => p.IsReady);

            return new SetReadyResult
            {
                Success = true,
                Message = isReady ? "已准备" : "取消准备",
                IsReady = isReady,
                CanStartGame = canStartGame
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "设置准备状态失败 - RoomId: {RoomId}, UserId: {UserId}", roomId, userId);
            return new SetReadyResult
            {
                Success = false,
                Message = "设置准备状态失败",
                Errors = { ex.Message }
            };
        }
    }

    public async Task<StartGameResult> StartGameAsync(Guid roomId, Guid userId, string? username = null)
    {
        try
        {
            var room = await _roomRepository.GetByIdAsync(roomId);
            if (room == null)
            {
                return new StartGameResult
                {
                    Success = false,
                    Message = "房间不存在",
                    Errors = { "房间不存在" }
                };
            }

            if (room.OwnerId != userId)
            {
                return new StartGameResult
                {
                    Success = false,
                    Message = "只有房主可以开始游戏",
                    Errors = { "只有房主可以开始游戏" }
                };
            }

            // 获取房间内所有玩家
            var players = await _roomPlayerRepository.GetManyAsync(rp => rp.RoomId == roomId);
            var playersList = players.ToList();

            if (playersList.Count < 2)
            {
                return new StartGameResult
                {
                    Success = false,
                    Message = "玩家人数不足，至少需要2人",
                    Errors = { "玩家人数不足，至少需要2人" }
                };
            }

            if (!playersList.All(p => p.IsReady))
            {
                return new StartGameResult
                {
                    Success = false,
                    Message = "所有玩家必须准备才能开始游戏",
                    Errors = { "所有玩家必须准备才能开始游戏" }
                };
            }

            room.StartGame();
            await _roomRepository.UpdateAsync(room);
            await _roomRepository.SaveChangesAsync();

            // 创建画线圈地游戏
            var gameSettings = new GameSettings
            {
                MapWidth = 1000,
                MapHeight = 1000,
                Duration = 180,
                MaxPlayers = playersList.Count
            };

            var hostPlayer = playersList.First(p => p.UserId == userId);
            var hostUser = await _userRepository.GetByIdAsync(userId);
            
            // 优先使用传入的用户名，如果没有则从数据库获取，最后回退到 "Unknown"
            string hostUsername = username ?? hostUser?.Username ?? "Unknown";
            
            _logger.LogDebug("[调试] 创建游戏 - HostUserId: {UserId}, PassedUsername: {PassedUsername}, DatabaseUsername: {DbUsername}, FinalUsername: {FinalUsername}", 
                userId, username, hostUser?.Username, hostUsername);

            var gameResult = await _lineDrawingGameService.CreateGameAsync(
                roomId.ToString(), 
                gameSettings, 
                userId, 
                hostUsername);

            if (!gameResult.Success)
            {
                return new StartGameResult
                {
                    Success = false,
                    Message = "创建游戏失败",
                    Errors = gameResult.Errors
                };
            }

            // 添加其他玩家到游戏
            foreach (var player in playersList.Where(p => p.UserId != userId))
            {
                // 尝试从导航属性获取用户信息，如果没有则查询数据库
                string playerUsername = player.User?.Username ?? "Unknown";
                
                if (playerUsername == "Unknown")
                {
                    var user = await _userRepository.GetByIdAsync(player.UserId);
                    playerUsername = user?.Username ?? "Unknown";
                }
                
                _logger.LogDebug("[调试] 添加玩家到游戏 - PlayerId: {UserId}, NavigationUsername: {NavUsername}, DatabaseUsername: {DbUsername}, FinalUsername: {FinalUsername}", 
                    player.UserId, player.User?.Username, playerUsername, playerUsername);
                
                await _lineDrawingGameService.JoinGameAsync(
                    roomId.ToString(), 
                    player.UserId, 
                    playerUsername);
            }

            // 立即启动游戏
            await _lineDrawingGameService.StartGameAsync(gameResult.GameId, userId);

            return new StartGameResult
            {
                Success = true,
                Message = "游戏开始",
                GameId = gameResult.GameId
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "开始游戏失败 - RoomId: {RoomId}", roomId);
            return new StartGameResult
            {
                Success = false,
                Message = "开始游戏失败",
                Errors = { ex.Message }
            };
        }
    }

    public async Task<bool> RoomExistsAsync(Guid roomId)
    {
        try
        {
            return await _roomRepository.ExistsAsync(r => r.Id == roomId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "检查房间存在时发生错误 - RoomId: {RoomId}", roomId);
            return false;
        }
    }

    public async Task<RoomDetail?> GetUserCurrentRoomAsync(Guid userId)
    {
        try
        {
            // 先从RoomPlayer表找到用户所在的房间
            var userRoomPlayer = await _roomPlayerRepository.GetSingleAsync(rp => rp.UserId == userId);
            if (userRoomPlayer == null)
            {
                return null;
            }

            return await GetRoomDetailAsync(userRoomPlayer.RoomId, userId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户当前房间失败 - UserId: {UserId}", userId);
            return null;
        }
    }

    public async Task<KickPlayerResult> KickPlayerAsync(Guid roomId, Guid ownerId, Guid targetUserId)
    {
        try
        {
            var room = await _roomRepository.GetByIdAsync(roomId);
            if (room == null)
            {
                return new KickPlayerResult
                {
                    Success = false,
                    Message = "房间不存在",
                    Errors = { "房间不存在" }
                };
            }

            if (room.OwnerId != ownerId)
            {
                return new KickPlayerResult
                {
                    Success = false,
                    Message = "只有房主可以踢出玩家",
                    Errors = { "只有房主可以踢出玩家" }
                };
            }

            var targetPlayer = await _roomPlayerRepository.GetSingleAsync(rp => rp.RoomId == roomId && rp.UserId == targetUserId);
            if (targetPlayer == null)
            {
                return new KickPlayerResult
                {
                    Success = false,
                    Message = "目标玩家不在房间中",
                    Errors = { "目标玩家不在房间中" }
                };
            }

            // 删除玩家记录
            await _roomPlayerRepository.DeleteAsync(targetPlayer);
            await _roomPlayerRepository.SaveChangesAsync();
            
            // 同步更新CurrentPlayers字段
            room.DecrementPlayerCount();
            await _roomRepository.UpdateAsync(room);
            await _roomRepository.SaveChangesAsync();

            return new KickPlayerResult
            {
                Success = true,
                Message = "玩家已被踢出"
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "踢出玩家失败 - RoomId: {RoomId}, TargetUserId: {TargetUserId}", roomId, targetUserId);
            return new KickPlayerResult
            {
                Success = false,
                Message = "踢出玩家失败",
                Errors = { ex.Message }
            };
        }
    }

    private string GetNextAvailableColor(List<RoomPlayer> players)
    {
        var availableColors = new[] { "red", "blue", "green", "yellow", "purple", "orange" };
        var usedColors = players.Where(p => !string.IsNullOrEmpty(p.PlayerColor))
                               .Select(p => p.PlayerColor)
                               .ToHashSet();

        return availableColors.FirstOrDefault(c => !usedColors.Contains(c)) ?? "gray";
    }

    public async Task<SendChatMessageResult> SendChatMessageAsync(Guid roomId, Guid userId, string message, string messageType = "text")
    {
        try
        {
            // 验证房间是否存在
            var room = await _roomRepository.GetByIdAsync(roomId);
            if (room == null)
            {
                return new SendChatMessageResult
                {
                    Success = false,
                    Message = "房间不存在",
                    Errors = { "房间不存在" }
                };
            }

            // 验证用户是否在房间中
            var roomPlayer = await _roomPlayerRepository.GetSingleAsync(rp => rp.RoomId == roomId && rp.UserId == userId);
            if (roomPlayer == null)
            {
                return new SendChatMessageResult
                {
                    Success = false,
                    Message = "您不在该房间中",
                    Errors = { "您不在该房间中" }
                };
            }

            // 验证消息内容
            if (string.IsNullOrWhiteSpace(message))
            {
                return new SendChatMessageResult
                {
                    Success = false,
                    Message = "消息内容不能为空",
                    Errors = { "消息内容不能为空" }
                };
            }

            if (message.Length > 500)
            {
                return new SendChatMessageResult
                {
                    Success = false,
                    Message = "消息内容过长，最多500字符",
                    Errors = { "消息内容过长，最多500字符" }
                };
            }

            // 获取用户信息
            var user = await _userRepository.GetByIdAsync(userId);
            if (user == null)
            {
                return new SendChatMessageResult
                {
                    Success = false,
                    Message = "用户不存在",
                    Errors = { "用户不存在" }
                };
            }

            // 创建聊天消息
            var chatMessage = RoomMessage.CreateUserMessage(roomId, userId, message);
            
            await _roomMessageRepository.AddAsync(chatMessage);
            await _roomMessageRepository.SaveChangesAsync();

            _logger.LogInformation("用户 {UserId} 在房间 {RoomId} 发送消息: {Message}", userId, roomId, message);

            return new SendChatMessageResult
            {
                Success = true,
                Message = "消息发送成功",
                MessageInfo = new ChatMessageInfo
                {
                    Id = chatMessage.Id,
                    RoomId = chatMessage.RoomId,
                    UserId = chatMessage.UserId,
                    Username = user.Username,
                    Message = chatMessage.Message,
                    MessageType = chatMessage.MessageType.ToString().ToLowerInvariant(),
                    CreatedAt = chatMessage.CreatedAt
                }
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "发送聊天消息失败 - RoomId: {RoomId}, UserId: {UserId}", roomId, userId);
            return new SendChatMessageResult
            {
                Success = false,
                Message = "发送聊天消息失败",
                Errors = { ex.Message }
            };
        }
    }

    public async Task<GetChatHistoryResult> GetChatHistoryAsync(Guid roomId, Guid userId, int limit = 50, int offset = 0)
    {
        try
        {
            // 验证参数
            if (limit <= 0 || limit > 100)
            {
                return new GetChatHistoryResult
                {
                    Success = false,
                    Message = "limit 参数必须在 1-100 之间",
                    Errors = { "limit 参数必须在 1-100 之间" }
                };
            }

            if (offset < 0)
            {
                return new GetChatHistoryResult
                {
                    Success = false,
                    Message = "offset 参数不能小于 0",
                    Errors = { "offset 参数不能小于 0" }
                };
            }

            // 验证房间是否存在
            var room = await _roomRepository.GetByIdAsync(roomId);
            if (room == null)
            {
                return new GetChatHistoryResult
                {
                    Success = false,
                    Message = "房间不存在",
                    Errors = { "房间不存在" }
                };
            }

            // 验证用户是否在房间中
            var roomPlayer = await _roomPlayerRepository.GetSingleAsync(rp => rp.RoomId == roomId && rp.UserId == userId);
            if (roomPlayer == null)
            {
                return new GetChatHistoryResult
                {
                    Success = false,
                    Message = "您不在该房间中",
                    Errors = { "您不在该房间中" }
                };
            }

            // 获取聊天消息
            var allMessages = await _roomMessageRepository.GetManyAsync(rm => rm.RoomId == roomId);
            var orderedMessages = allMessages.OrderByDescending(rm => rm.CreatedAt).Skip(offset).Take(limit).ToList();

            // 获取用户信息并构建响应
            var chatMessages = new List<ChatMessageInfo>();
            foreach (var msg in orderedMessages.OrderBy(rm => rm.CreatedAt)) // 按时间正序返回
            {
                var msgUser = await _userRepository.GetByIdAsync(msg.UserId);
                chatMessages.Add(new ChatMessageInfo
                {
                    Id = msg.Id,
                    RoomId = msg.RoomId,
                    UserId = msg.UserId,
                    Username = msgUser?.Username ?? "未知用户",
                    Message = msg.Message,
                    MessageType = msg.MessageType.ToString().ToLowerInvariant(),
                    CreatedAt = msg.CreatedAt
                });
            }

            var totalCount = allMessages.Count();

            _logger.LogDebug("获取房间 {RoomId} 聊天历史，返回 {Count} 条消息", roomId, chatMessages.Count);

            return new GetChatHistoryResult
            {
                Success = true,
                Message = "获取聊天历史成功",
                Messages = chatMessages,
                Total = totalCount,
                Limit = limit,
                Offset = offset
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取聊天历史失败 - RoomId: {RoomId}, UserId: {UserId}", roomId, userId);
            return new GetChatHistoryResult
            {
                Success = false,
                Message = "获取聊天历史失败",
                Errors = { ex.Message }
            };
        }
    }
}